package com.xms.form.service;

import com.xms.core.exception.XmsException;
import com.xms.datacore.service.CreaterService;
import com.xms.form.entity.SystemForm;
import com.xms.schema.entity.Entity;
import com.xms.utils.CollectionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.SQLException;
import java.util.Collection;

/**
 * <p>
 * SystemformCreaterService
 * </p>
 *
 * @author migo
 * @since 2021/9/3
 */
@CacheConfig(cacheNames = "systemform", keyGenerator = "CacheKeyGenerator")
@Service
public class SystemFormCreaterService extends CreaterService<SystemForm> implements ISystemFormCreaterService {
    private IDefaultSystemformProvider _defaultSystemformProvider;
    private ISystemFormDependency _systemFormDependency;

    @Autowired
    public SystemFormCreaterService(IDefaultSystemformProvider defaultSystemformProvider,
                                    ISystemFormDependency systemFormDependency) {
        _defaultSystemformProvider = defaultSystemformProvider;
        _systemFormDependency = systemFormDependency;
    }

    @CacheEvict(allEntries = true, condition = "#result == true")
    @Transactional(rollbackFor=Exception.class)
    @Override
    public boolean create(SystemForm entity) throws SQLException, XmsException {
        if (entity.getFormconfig().isEmpty()) {
            throw new XmsException("formconfig is required");
        }
        //依赖项
        _systemFormDependency.create(entity);
        return super.save(entity);
    }

    @CacheEvict(allEntries = true, condition = "#result == true")
    @Override
    public boolean createDefaultForm(Entity entity) throws XmsException, SQLException {
        return this.create(_defaultSystemformProvider.get(entity));
    }

    @CacheEvict(allEntries = true, condition = "#result == true")
    @Transactional(rollbackFor=Exception.class)
    @Override
    public boolean createMany(Collection<SystemForm> entityList) throws SQLException, XmsException {
        if (CollectionUtil.notEmpty(entityList)) {
            for (SystemForm entity : entityList) {
                this.create(entity);
            }
        }
        return true;
    }
}
